package com.ruitu.mall_98_2.order;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.ClipboardUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.TimeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.dialog.CustomAlertDialog;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.mine.AfterSaleActivity;
import com.ruitu.mall_98_2.mvp.contract.OrderDetailsContract;
import com.ruitu.mall_98_2.mvp.model.OrderDetailsModel;
import com.ruitu.mall_98_2.mvp.presenter.OrderDetailsPresenter;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.order.OrderDetail;
import com.ruitu.router_module.bean.order.SmallOrder;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.share.ShareUtil;
import com.ruitu.router_module.share.uitool.ShareBoard;
import com.ruitu.router_module.share.uitool.ShareBoardlistener;
import com.ruitu.router_module.share.uitool.SnsPlatform;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;

public class OrderDetailsActivity extends MyBaseActivity<OrderDetailsPresenter, OrderDetailsModel> implements OrderDetailsContract.View {
    private SmallOrder orderDetail;

    private TextView tv_waiting_pay_commodity_total;//商品
    private TextView tv_waiting_pay_expressage_total;//运费
    private TextView tv_waiting_pay_order_total;//订单的金额
    private RelativeLayout rl_coupon;
    private TextView discountTotal;//满减优惠券
    private TextView tv_waiting_pay_actual_money;//需付款
    private TextView tv_order_number;//订单编号
    private TextView tv_copy;//复制
    private TextView tv_creat_time;//订单创建时间
    private TextView tv_pay_time;//付款时间
    private TextView tv_pay_type;//付款方式

    private TextView tv_consignee; //姓名
    private TextView tv_tel;//手机号
    private TextView tv_address;//地址
    private TextView tv_order_status;//订单状态

    private TextView tv_company_name;
    private ImageView iv_company_logo;//公司logo
    private ImageView iv_commodity;
    private TextView tv_commodity_name;
    private TextView tv_commodity_info;
    private TextView tv_commodity_price;
    private TextView tv_commodity_num;
    private TextView tv_check_logistics;//查看物流
    private TextView tv_ok;//确认收货
    private TextView tv_return;//退换

    private TextView tv_comment;//评论
    private TextView tv_delete;//删除订单
    private TextView tv_invite;//邀请拼团
    private TextView tv_application_for_drawback;//邀请拼团
    private TextView tv_group_booking_now_num;//当前拼团人数
    private TextView tv_group_booking_need_num;//需要拼团人数
    private TextView tv_group_booking_time;//拼团结束的剩余时间
    private TextView tv_group_booking_end_time;//拼团结束的时间
    private TextView tv_group_booking_status;//拼团的状态

    private TextView tv_advance;//预付定金
    private TextView tv_tail_money;//尾款
    private TextView tv_send_time;//预计发货时间
    //    private TextView tv_shop_price;//预订单的商家报价
    private TextView tv_advance_ratio;//预订单的支付比例
//    private TextView tv_waiting_pay_actual_money_status;
//    private RelativeLayout rl_goods_spec;//
//    private LinearLayout ll_agree;//卖家同意交易显示


    private LinearLayout ll_waiting_reciever;
    private LinearLayout ll_pay_type;
    private LinearLayout ll_cancle;
    private LinearLayout ll_pay_time;
    private LinearLayout ll_group_booking;//拼团
    private LinearLayout ll_advance;//预订
    private RelativeLayout rl_waiting_send;

    private RelativeLayout rl_company;//企业
    private RelativeLayout rl_group_booking_end_time;//结束时间
    private RelativeLayout rl_order_status;//订单的状态
    private LinearLayout ll_commmodity_item;//商品
    private LinearLayout ll_xiajia;//下架

    private String webUrl;
    private List<Integer> skipId = new ArrayList<>();

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_order_details;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return findViewById(R.id.progress);
    }


    CustomAlertDialog customAlertDialog;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        bundle.putSerializable("smallOrder", orderDetail);
        if (v == tv_copy) {
            ClipboardUtils.copyText(tv_order_number.getText().toString());
            ToastUtils.showShort("已复制到粘贴板");
        }

        if (v == tv_check_logistics) {
            startActivity(CheckLogisticsActivity.class, bundle);
        }

        if (v == tv_ok) {
            customAlertDialog = new CustomAlertDialog(this, "确定确认收货吗?", new CustomAlertDialog.OkOnClickListener() {
                @Override
                public void OkOnClick() {
                    showProgress();
                    mPresenter.qrsh(orderDetail.getId());
                    customAlertDialog.dismiss();
                }

            });
            customAlertDialog.show();
        }

        if (v == tv_comment) {
            Logg.i(orderDetail.toString());
            startActivity(CommentActivity.class, bundle);
        }

        if (v == tv_delete) {
            customAlertDialog = new CustomAlertDialog(this, "确定删除该订单吗?", new CustomAlertDialog.OkOnClickListener() {
                @Override
                public void OkOnClick() {
                    showProgress();
                    mPresenter.deleteOrder(orderDetail.getOrderId());
                }
            });
            customAlertDialog.show();
        }

        if (v == tv_invite) {
            showProgress();
            mPresenter.invitationCollage(orderDetail.getGoodsId());
        }

        if (v == tv_return) {
            Logg.i(orderDetail.toString());
            startActivity(AfterSaleActivity.class, bundle);
        }

        if (tv_application_for_drawback == v) {
            Logg.i(orderDetail.toString());
            startActivity(AfterSaleActivity.class, bundle);
        }

        if (rl_company == v) {
            try {
                bundle.putString("companyId", orderDetail.getCompanyId());
                A_Rutils.startActivity(this, "com.ruitu.mall_98_1.product.activity.ShopDetailActivity", bundle);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        if (ll_commmodity_item == v) {
            Product product = new Product();
            product.setGoodId(orderDetail.getGoodsId());
            bundle.putSerializable("product", product);
            try {
                A_Rutils.startActivity(this, "com.ruitu.mall_98_1.product.activity.ProductDetailActivity", bundle);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private SmallOrder smallOrder;

    @Override
    protected void initViews() {
        super.initViews();
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
        setHeadTitle("订单详情");
        showEmptyView(skipId);
        smallOrder = (SmallOrder) getIntent().getExtras().get("smallOrder");
        tv_waiting_pay_commodity_total = findViewById(R.id.tv_waiting_pay_commodity_total);
        tv_waiting_pay_expressage_total = findViewById(R.id.tv_waiting_pay_expressage_total);
        tv_waiting_pay_order_total = findViewById(R.id.tv_waiting_pay_order_total);
        tv_waiting_pay_actual_money = findViewById(R.id.tv_waiting_pay_actual_money);
        tv_order_number = findViewById(R.id.tv_order_number);
        tv_creat_time = findViewById(R.id.tv_creat_time);
        tv_pay_time = findViewById(R.id.tv_pay_time);
        tv_pay_type = findViewById(R.id.tv_pay_type);
        tv_copy = findViewById(R.id.tv_copy);
        discountTotal = findViewById(R.id.tv_discountTotal);
        rl_coupon = findViewById(R.id.rl_coupon);
        tv_consignee = findViewById(R.id.tv_consignee);
        tv_tel = findViewById(R.id.tv_tel);
        tv_address = findViewById(R.id.tv_address);
        tv_order_status = findViewById(R.id.tv_order_status);
//        ll_agree = findViewById(R.id.ll_agree);
        rl_waiting_send = findViewById(R.id.rl_waiting_send);
        rl_company = findViewById(R.id.rl_company);
        rl_group_booking_end_time = findViewById(R.id.rl_group_booking_end_time);
        tv_group_booking_status = findViewById(R.id.tv_group_booking_status);
        ll_commmodity_item = findViewById(R.id.ll_commmodity_item);
        ll_xiajia = findViewById(R.id.ll_xiajia);
        rl_order_status = findViewById(R.id.rl_order_status);

        tv_company_name = findViewById(R.id.tv_company_name);
        iv_company_logo = findViewById(R.id.iv_company_logo);
        iv_commodity = findViewById(R.id.iv_commodity);
        tv_commodity_name = findViewById(R.id.tv_commodity_name);
        tv_commodity_info = findViewById(R.id.tv_commodity_info);
        tv_commodity_price = findViewById(R.id.tv_commodity_price);
        tv_commodity_num = findViewById(R.id.tv_commodity_num);
        tv_check_logistics = findViewById(R.id.tv_check_logistics);
        tv_group_booking_now_num = findViewById(R.id.tv_group_booking_now_num);
        tv_group_booking_need_num = findViewById(R.id.tv_group_booking_need_num);
        tv_group_booking_time = findViewById(R.id.tv_group_booking_time);
        tv_group_booking_end_time = findViewById(R.id.tv_group_booking_end_time);
        tv_ok = findViewById(R.id.tv_ok);
        tv_comment = findViewById(R.id.tv_comment);
        tv_delete = findViewById(R.id.tv_delete);
        tv_invite = findViewById(R.id.tv_invite);
        tv_return = findViewById(R.id.tv_return);
        tv_application_for_drawback = findViewById(R.id.tv_application_for_drawback);

        tv_advance = findViewById(R.id.tv_advance);
        tv_tail_money = findViewById(R.id.tv_tail_money);
        tv_send_time = findViewById(R.id.tv_send_time);
//        tv_shop_price = findViewById(R.id.tv_shop_price);
        tv_advance_ratio = findViewById(R.id.tv_advance_ratio);
//        tv_waiting_pay_actual_money_status = findViewById(R.id.tv_waiting_pay_actual_money_status);

        ll_waiting_reciever = findViewById(R.id.ll_waiting_reciever);
        ll_pay_type = findViewById(R.id.ll_pay_type);
        ll_cancle = findViewById(R.id.ll_cancle);
        ll_pay_time = findViewById(R.id.ll_pay_time);
        ll_group_booking = findViewById(R.id.ll_group_booking);
        ll_advance = findViewById(R.id.ll_advance);
//        rl_goods_spec = findViewById(R.id.rl_goods_spec);

        tv_copy.setOnClickListener(this);
        tv_check_logistics.setOnClickListener(this);
        tv_ok.setOnClickListener(this);
        tv_comment.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        tv_invite.setOnClickListener(this);
        tv_return.setOnClickListener(this);
        tv_application_for_drawback.setOnClickListener(this);
        rl_company.setOnClickListener(this);
        ll_commmodity_item.setOnClickListener(this);
        getData();
    }

    private void getData() {
        showProgress();
        mPresenter.orderDetailsInfo(smallOrder.getId());
    }

    private void initData() {

        SmallOrder.OrderBean order = orderDetail.getOrder();
        tv_consignee.setText(order.getConsigneeName());
        tv_address.setText(order.getOrderProvinceCode() + order.getOrderCityCode() + order.getOrderCountyCode() + order.getCollectGoodsAddress());
        tv_tel.setText(order.getCollectGoodsPhone());
        tv_company_name.setText(orderDetail.getCompanyName());
        tv_waiting_pay_commodity_total.setText(orderDetail.getGoodsTotal() + "元");
        tv_waiting_pay_expressage_total.setText(orderDetail.getFreight() + "元");
        tv_waiting_pay_order_total.setText(orderDetail.getOrderTotal() + "元");
        tv_waiting_pay_actual_money.setText("￥" + orderDetail.getOrderTotal());
        tv_order_number.setText(orderDetail.getId());
        tv_creat_time.setText(TimeUtils.millis2String(orderDetail.getCreateTime()));
        Glide.with(this).load(Config.BASE_URL + orderDetail.getGoodsUrl()).apply(Arad.opts).into(iv_commodity);
        Glide.with(this).load(Config.BASE_URL + orderDetail.getCompanyLogo()).apply(Arad.opts_shop).into(iv_company_logo);
        tv_commodity_name.setText(orderDetail.getGoodsName());
        tv_commodity_info.setText(orderDetail.getSkuContent());
        tv_commodity_price.setText("￥" + orderDetail.getGoodsPrice());
        tv_commodity_num.setText("x" + orderDetail.getQuantity());
        discountTotal.setText(orderDetail.getDiscountTotal() + "元");
        tv_pay_time.setText(TimeUtils.millis2String(orderDetail.getPayTime()));
        switch (orderDetail.getOrderStatus()) {
            case "0":
                if (order.getIsPayOver().equals("2")) {
                    tv_order_status.setText("已支付订金");
                } else if (order.getIsPayOver().equals("4")) {
                    tv_order_status.setText("等待支付尾款");
                } else if (order.getIsPayOver().equals("0")) {
                    tv_order_status.setText("等待支付订金");
                } else {
                    tv_order_status.setText("未支付");
                }
                break;
            case "1":
                ll_cancle.setVisibility(View.VISIBLE);
                tv_invite.setVisibility(View.GONE);
                tv_order_status.setText("已取消");
                if (TextUtils.equals(smallOrder.getGoodStatus(),"0")){
                    ll_xiajia.setVisibility(View.VISIBLE);
                }else if (TextUtils.equals(smallOrder.getGoodStatus(),"1")){
                    ll_xiajia.setVisibility(View.GONE);
                }
                break;
            case "2":
//                if (!orderDetail.getOrderType().equals("3")) {
                tv_order_status.setText("待发货");
//                }
                rl_waiting_send.setVisibility(View.VISIBLE);

                break;
            case "4":
                ll_waiting_reciever.setVisibility(View.VISIBLE);
                tv_comment.setVisibility(View.GONE);
                tv_order_status.setText("已发货");
                tv_invite.setVisibility(View.GONE);
                break;
            case "5":
//                ll_waiting_comment.setVisibility(View.VISIBLE);
                ll_waiting_reciever.setVisibility(View.VISIBLE);
                tv_ok.setVisibility(View.GONE);
                tv_order_status.setText("已收货");
                tv_invite.setVisibility(View.GONE);
                break;
            case "6":
                tv_order_status.setText("申请售后中");
                tv_invite.setVisibility(View.GONE);
                break;
            case "7":
                tv_order_status.setText("已完成");
                ll_waiting_reciever.setVisibility(View.VISIBLE);
                tv_check_logistics.setVisibility(View.GONE);
                tv_ok.setVisibility(View.GONE);
                tv_comment.setVisibility(View.GONE);
                tv_invite.setVisibility(View.GONE);
                if (TextUtils.equals(smallOrder.getGoodStatus(),"0")){
                    ll_xiajia.setVisibility(View.VISIBLE);
                }else if (TextUtils.equals(smallOrder.getGoodStatus(),"1")){
                    ll_xiajia.setVisibility(View.GONE);
                }
                break;
            case "8":
                tv_order_status.setText("退款完成");
                tv_invite.setVisibility(View.GONE);
                break;
            default:
                break;
        }
        if (TextUtils.equals(orderDetail.getOrderType(), "1")) {
            SmallOrder.GoodsPreSale goodsReserve = orderDetail.getGoodsPreSale();
            if (goodsReserve != null) {
                ll_advance.setVisibility(View.VISIBLE);
                tv_advance_ratio.setText(goodsReserve.getPreSaleRatio() + "%");
                tv_advance.setText("￥" + orderDetail.getOrder().getAdvanceMoney());
                tv_tail_money.setText("￥" + orderDetail.getOrder().getTailMoney());
                tv_send_time.setText("付款后"+goodsReserve.getPreSaleDelivey()+"天");
            }
        }
        if (TextUtils.equals(orderDetail.getOrderType(), "2")) {
            SmallOrder.GoodsReserve goodsReserve = orderDetail.getGoodsReserve();
            if (goodsReserve != null) {
                ll_advance.setVisibility(View.VISIBLE);
                tv_advance_ratio.setText(goodsReserve.getAdvanceRatio() + "%");
                tv_advance.setText("￥" + orderDetail.getOrder().getAdvanceMoney());
                tv_tail_money.setText("￥" + orderDetail.getOrder().getTailMoney());
                tv_send_time.setText(TimeUtils.millis2String(goodsReserve.getDeliveryTime(),new SimpleDateFormat("yyyy-MM-dd")));
            }

        } else if (TextUtils.equals(orderDetail.getOrderType(), "3")) {

            if (orderDetail.getGoodsCollage() == null) {
                ll_group_booking.setVisibility(View.GONE);
            } else {
                if (TextUtils.equals(order.getCollageStatus(), "2")) {
                    tv_invite.setVisibility(View.VISIBLE);
                    tv_group_booking_status.setText("进行中");
                    tv_group_booking_now_num.setText(orderDetail.getGoodsCollage().getExistingNum().trim() + "人");
                    tv_group_booking_need_num.setText(orderDetail.getGoodsCollage().getCollageNum().trim() + "人");
                    ll_group_booking.setVisibility(View.VISIBLE);
                    tv_group_booking_end_time.setText(TimeUtils.millis2String(orderDetail.getGoodsCollage().getEndTime()));
//                tv_group_booking_time.setText("剩余时间: " + TimeUtils.getFitTimeSpan(TimeUtils.millis2String(System.currentTimeMillis()), TimeUtils.millis2String(orderDetail.getGoodsCollage().getEndTime()), 4));
                    rl_waiting_send.setVisibility(View.GONE);
                    rl_group_booking_end_time.setVisibility(View.VISIBLE);
                    rl_order_status.setVisibility(View.GONE);

                } else if (TextUtils.equals(order.getCollageStatus(), "1")){
                    if (orderDetail.getOrderStatus().equals("2")) {
                        tv_invite.setVisibility(View.GONE);
                        tv_group_booking_status.setText("已完成");
                        tv_group_booking_now_num.setText(orderDetail.getGoodsCollage().getExistingNum().trim() + "人");
                        tv_group_booking_need_num.setText(orderDetail.getGoodsCollage().getCollageNum().trim() + "人");
                        ll_group_booking.setVisibility(View.VISIBLE);
//                    tv_group_booking_end_time.setText(TimeUtils.millis2String(orderDetail.getGoodsCollage().getEndTime()));
                        tv_group_booking_time.setText("等待卖家发货");
                        rl_group_booking_end_time.setVisibility(View.GONE);
                    }
                }else {
                    tv_invite.setVisibility(View.GONE);
                    tv_group_booking_status.setText("已超时");
                    tv_group_booking_now_num.setText(orderDetail.getGoodsCollage().getExistingNum().trim() + "人");
                    tv_group_booking_need_num.setText(orderDetail.getGoodsCollage().getCollageNum().trim() + "人");
                    ll_group_booking.setVisibility(View.VISIBLE);
                    tv_group_booking_end_time.setText(TimeUtils.millis2String(orderDetail.getGoodsCollage().getEndTime()));
//                tv_group_booking_time.setText("剩余时间: " + TimeUtils.getFitTimeSpan(TimeUtils.millis2String(System.currentTimeMillis()), TimeUtils.millis2String(orderDetail.getGoodsCollage().getEndTime()), 4));
                    rl_waiting_send.setVisibility(View.GONE);
                    rl_group_booking_end_time.setVisibility(View.VISIBLE);
                    rl_order_status.setVisibility(View.GONE);
                }
            }
//            }
        }
        if (!TextUtils.isEmpty(orderDetail.getPaymentType())) {
            switch (orderDetail.getPaymentType()) {
                case "0":
                    tv_pay_type.setText("微信");
                    break;
                case "1":
                    tv_pay_type.setText("支付宝");
                    break;
                case "3":
                    tv_pay_type.setText("余额支付");
                    break;
            }

        } else {
            ll_pay_type.setVisibility(View.GONE);
            ll_pay_time.setVisibility(View.GONE);
        }


        //根据分润的状态判断是否显示
        if (TextUtils.equals(orderDetail.getShareStatus(),"0")){
            tv_return.setVisibility(View.VISIBLE);
        }else {
            tv_return.setVisibility(View.GONE);
        }
    }

    @Override
    public void setData(OrderDetail orderDetail) {
        this.orderDetail = orderDetail.getOrderDetails();
        if (orderDetail != null) {
            showContent(null);
            initData();
        } else {
            showEmptyView(skipId);
        }
    }

    @Override
    public void setSuc() {
        finish();
    }

    @Override
    public void setInvitationSuc(String data) {
        webUrl = data;
        showShare();
    }

    @Override
    public void setFail() {
        showError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
    }

    private ShareBoard mShareBoard;//分享面板

    private void showShare() {

        mShareBoard = ShareUtil.getShareBoard(this);
        mShareBoard.setShareboardclickCallback(new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, String platform) {
                hideProgress();
                showProgressWithText(true, "打开分享...");
                ShareParams params = ShareUtil.getShareParams("我在九八商城拼了一件不错的商品，快来围观！"
                        , orderDetail.getGoodsName(), Config.BASE_URL + webUrl);
                JShareInterface.share(platform, params, new PlatActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        hideProgress();
                        ToastUtils.showShortSafe("分享成功");
                    }

                    @Override
                    public void onError(Platform platform, int i, int i1, Throwable throwable) {
                        hideProgress();
                        ToastUtils.showShortSafe("分享错误");

                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        hideProgress();
                        ToastUtils.showShortSafe("分享取消");
                    }
                });
            }
        });
        try {
            mShareBoard.show();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShortSafe("发生了一些错误,请稍后重试");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setOrderDetailFinish(EventModel eventModel) {
        if (eventModel.getEventCode() == 18122000) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }
}
